package com.capinfo.accumulation.service.collection.impl;

import com.capinfo.accumulation.model.collection.Company;
import com.capinfo.accumulation.model.collection.CompanyAccountFund;
import com.capinfo.accumulation.model.collection.CompanyHistory;
import com.capinfo.accumulation.parameter.collection.CompanyParameter;
import com.capinfo.accumulation.service.collection.CompanyHistoryService;
import com.capinfo.accumulation.service.collection.CompanyService;
import com.capinfo.commons.project.service.region.RegionService;
import com.capinfo.framework.dao.SearchCriteriaBuilder;
import com.capinfo.framework.dao.impl.restriction.RestrictionExpression;
import com.capinfo.framework.exception.ObjectNotFoundException;
import com.capinfo.framework.service.impl.CommonsDataOperationServiceImpl;
import com.capinfo.framework.util.LogUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by wangyulin on 2017/9/27.
 */
public class CompanyServiceImpl extends CommonsDataOperationServiceImpl<Company, CompanyParameter> implements CompanyService {

    private static final Log logger = LogFactory.getLog(RegionService.class);

    @Autowired
    private CompanyHistoryService historyService;

    public List<Company> getAllCompanys() {

        return getGeneralService().getAllObjects(Company.class);
    }

    public Company isExist(CompanyParameter parameter) {

        Company company = parameter.getEntity();

        SearchCriteriaBuilder<Company> searchCriteriaBuilder = new SearchCriteriaBuilder<Company>(Company.class);
        if (StringUtils.isBlank(parameter.getCompanyCode()))
            return null;

        //18位-统一社会信用代码(creditCode)

        if (parameter.getCompanyCode().length() == 18) {

            searchCriteriaBuilder.addQueryCondition("creditCode", RestrictionExpression.EQUALS_OP, parameter.getCompanyCode());
        } else if (parameter.getCompanyCode().length() == 9) {  //9位-主管机构代码（competentCode）
            searchCriteriaBuilder.addQueryCondition("competentCode", RestrictionExpression.EQUALS_OP, parameter.getCompanyCode());
        } else if (parameter.getCompanyCode().length() == 12) {
            searchCriteriaBuilder.addQueryCondition("competentCode", RestrictionExpression.EQUALS_OP, "生成的12位");
        }
        List<Company> companys = this.getGeneralService().getObjects(searchCriteriaBuilder.build());
        if (companys == null || companys.size() == 0)
            return null;
        return companys.get(0);


    }

    public boolean audit(CompanyParameter parameter) {
        Company curCompany = parameter.getEntity();
        Company company;
        CompanyAccountFund companyAccountFund;
        CompanyHistory companyHistory = null;

        if (curCompany.getId() != null) {
            companyHistory = historyService.getCompanyHistoryById(curCompany.getId());
            if (companyHistory == null)
                return false;

            company = new Company();
            companyAccountFund = new CompanyAccountFund();
            BeanUtils.copyProperties(companyHistory, company,
                    new String[]{"id", "companyId", "siteId"});

            BeanUtils.copyProperties(companyHistory.getCompanyAccountHistories().get(0), companyAccountFund,
                    new String[]{"id", "companyAccountFundId"});

            parameter.setEntity(company);
            parameter.setCompanyAccount(companyAccountFund);
        } else {
            return false;
        }
        company = this.saveOrUpdate(parameter);
        if (company.getId() != null) {
            if (!StringUtils.isBlank(parameter.getConfirmerId()))
                historyService.auditInfo(curCompany.getId(), company.getId(), Long.parseLong(parameter.getConfirmerId()));
            else
                historyService.auditInfo(curCompany.getId(), company.getId(), null);
        } else {
            return false;
        }
        return true;
    }


    @Override
    public Company saveOrUpdate(CompanyParameter parameter) {

        Company entity = parameter.getEntity();
        CompanyAccountFund companyAccountFund = parameter.getCompanyAccount();
        //将公积金账号关联到公司对象中
        entity.getCompanyAccountFunds().add(companyAccountFund);
        if (null == entity.getId()) {

            if (entity.getLegalPersonality() == null)
                entity.setLegalPersonality(false);
            getGeneralService().persist(entity);

            return entity;
        } else {
            return entity;
        }
    }

    @Override
    public SearchCriteriaBuilder<Company> getSearchCriteriaBuilder(CompanyParameter parameter) {
        SearchCriteriaBuilder<Company> searchCriteriaBuilder = super.getSearchCriteriaBuilder(parameter);

        searchCriteriaBuilder.addQueryCondition("gbCompanyName", RestrictionExpression.LIKE_OP, parameter.getEntity().getGbCompanyName());
        searchCriteriaBuilder.addQueryCondition("gbOrganizationCode", RestrictionExpression.EQUALS_OP, parameter.getEntity().getGbOrganizationCode());
//        searchCriteriaBuilder.addQueryCondition("companyAccountFunds[1].accumulationFundAccountType.name", RestrictionExpression.EQUALS_OP, "补充");
//        searchCriteriaBuilder.addOrderCondition("id", SearchCriteria.OrderRow.ORDER_ASC);
        return searchCriteriaBuilder;
    }

    @Override
    public List<Company> getList(CompanyParameter parameter, long dataTotalCount, int currentPieceNum) {




        return super.getList(parameter, dataTotalCount, currentPieceNum);
    }

    public Company getCompanyById(Long id) {
        Company company = null;
        try {
            if (id == null)
                return null;
            company = getGeneralService().getObjectById(Company.class, id);
        } catch (ObjectNotFoundException e) {
            LogUtils.debugException(logger, e);
        }
        return company;
    }

    @Override
    public Company getCompany(CompanyParameter parameter) {
        SearchCriteriaBuilder<Company> searchCriteriaBuilder = new SearchCriteriaBuilder<Company>(Company.class);
        //组织机构代码
        searchCriteriaBuilder.addQueryCondition("gbCompanyName", RestrictionExpression.EQUALS_OP, parameter.getEntity().getGbCompanyName());
        //信用代码
        searchCriteriaBuilder.addQueryCondition("creditCode", RestrictionExpression.EQUALS_OP, parameter.getEntity().getCreditCode());
        //单位账号
        searchCriteriaBuilder.addQueryCondition("gbCompanyAccount", RestrictionExpression.EQUALS_OP, parameter.getEntity().getGbCompanyAccount());
        //单位id
        searchCriteriaBuilder.addQueryCondition("id", RestrictionExpression.EQUALS_OP, parameter.getEntity().getId());

        //单位账号
        searchCriteriaBuilder.addQueryCondition("gbCompanyAccount", RestrictionExpression.EQUALS_OP, parameter.getGbCompanyAccount());

        // TODO: 2017/10/24  //基本natureAccount
        searchCriteriaBuilder.addQueryCondition("natureAccount.name", RestrictionExpression.EQUALS_OP, "一般账户");
        long count = getGeneralService().getCount(searchCriteriaBuilder.build());
        if(count>0){
            List<Company> objects = getGeneralService().getObjects(searchCriteriaBuilder.build());
            return objects.get(0);
        }else{
            return  null;
        }
    }

    //保存变更的网点信息
    @Override
    public Company saveChangeSiteCompany(CompanyParameter parameter) {

        Company companyRecord = this.getObjectById(parameter);

        companyRecord.setPaymentSite(parameter.getEntity().getPaymentSite());

        companyRecord.setCompanyHistoryId(parameter.getCompanyHistoryId());

        getGeneralService().clear();

        getGeneralService().update(companyRecord);

        return companyRecord;


    }

    //单位基本信息的获取
    //fjs
    @Override
    public Company basicInfo(CompanyParameter companyParameter) {
        SearchCriteriaBuilder<Company> searchCriteriaBuilder = new SearchCriteriaBuilder<Company>(Company.class);
        //历史Id
        searchCriteriaBuilder.addQueryCondition("companyHistoryId", RestrictionExpression.EQUALS_OP, companyParameter.getCompanyHistoryId());

        List<Company> companys = this.getGeneralService().getObjects(searchCriteriaBuilder.build());
        if (companys == null || companys.size() == 0)
            return null;
        Company company=companys.get(0);
        return company;
    }

    @Override
    public Company saveCompanyBasicInfo(CompanyParameter parameter) {
        //根据ID取出对应的一条数据
        Company companyRecord = this.getObjectById(parameter);
        //赋值
        companyRecord.setGbCompanyName(parameter.getEntity().getGbCompanyName());
        companyRecord.setCompetentCode(parameter.getEntity().getCompetentCode());
        companyRecord.setCompanyAddress(parameter.getEntity().getCompanyAddress());
        companyRecord.setCompanyRelatoinshipsId(parameter.getEntity().getCompanyRelatoinshipsId());
        companyRecord.setCompanyEconomicTypeId(parameter.getEntity().getCompanyEconomicTypeId());
        companyRecord.setLegalPersonality(parameter.getEntity().getLegalPersonality());
        companyRecord.setGbLegalPersonName(parameter.getEntity().getGbLegalPersonName());
        companyRecord.setGbLegalPersonName(parameter.getEntity().getGbLegalPersonName());
        companyRecord.setLegalPersonIdCardTypeId(parameter.getEntity().getLegalPersonIdCardTypeId());
        companyRecord.setLegalPersonMobilePhone(parameter.getEntity().getLegalPersonMobilePhone());
        companyRecord.setContactName(parameter.getEntity().getContactName());
        companyRecord.setContactIdCardTypeId(parameter.getEntity().getContactIdCardTypeId());
        companyRecord.setContactIdCardNumber(parameter.getEntity().getContactIdCardNumber());
        companyRecord.setContactMobilePhone(parameter.getEntity().getContactMobilePhone());
        //历史ID
        companyRecord.setCompanyHistoryId(parameter.getEntity().getCompanyHistoryId());

        getGeneralService().clear();

        getGeneralService().update(companyRecord);

        return companyRecord;
    }
}
